package com.tjw.ec.auth.service;

import com.tjw.ec.common.core.constant.HttpConstants;
import com.tjw.ec.common.core.exception.BusinessException;
import com.tjw.ec.common.core.exception.ServiceException;
import com.tjw.ec.common.core.util.Response;
import com.tjw.ec.upms.api.dto.PermitVO;
import com.tjw.ec.upms.api.dto.RoleVO;
import com.tjw.ec.upms.api.entity.UserAccountEntity;
import com.tjw.ec.upms.api.feign.RemoteActionService;
import com.tjw.ec.upms.api.feign.RemotePermitService;
import com.tjw.ec.upms.api.feign.RemoteRoleService;
import com.tjw.ec.upms.api.feign.RemoteUserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Thinkpad
 * @create 2019/6/10
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteActionService remoteActionService;

    @Autowired
    private RemoteUserAccountService remoteUserAccountService;

    @Autowired
    private RemoteRoleService remoteRoleService;

    @Autowired
    private RemotePermitService remotePermitService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查询账户信息
        Response<UserAccountEntity> userAccountEntity = remoteUserAccountService.getUserAccountByUsername(username);

        if (userAccountEntity == null || userAccountEntity.getCode() == HttpConstants.FAIL) {
            throw new UsernameNotFoundException("用户:" + username + ",不存在!");
        }

        UserAccountEntity userAccountEntityData = userAccountEntity.getData();
        if (StringUtils.isEmpty(userAccountEntityData.getUserId())) {
            throw new BusinessException("用户信息位空！");
        }

        // 用户角色和权限集合
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();

        // 获取角色
        Response<List<RoleVO>> roles = remoteRoleService.getRoleByUserId(userAccountEntityData.getUserId());
        if (roles.getCode() == HttpConstants.SUCCESS) {
            List<RoleVO> rolesData = roles.getData();
            for (RoleVO role : rolesData) {
                //角色必须是ROLE_开头，可以在数据库中设置
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + role.getRoleName());
                grantedAuthorities.add(grantedAuthority);
            }
        } else {
            throw new ServiceException("服务异常！");
        }

        //获取权限
        Response<List<PermitVO>> permits = remotePermitService.getPermitByUserId(userAccountEntityData.getUserId());
        if (permits.getCode() == HttpConstants.SUCCESS) {
            List<PermitVO> permitsData = permits.getData();
            for (PermitVO permit : permitsData) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permit.getPermitValue());
                grantedAuthorities.add(grantedAuthority);
            }
        } else {
            throw new ServiceException("服务异常！");
        }

        boolean enabled = true; // 可用性 :true:可用 false:不可用
        boolean accountNonExpired = true; // 过期性 :true:没过期 false:过期
        boolean credentialsNonExpired = true; // 有效性 :true:凭证有效 false:凭证无效
        boolean accountNonLocked = true; // 锁定性 :true:未锁定 false:已锁定

        return new User(userAccountEntityData.getUsername(), userAccountEntityData.getPassword(),
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
    }
}